<template>
  <div class="content-box" v-loading="!dataLoaded">
    <div class="content" v-if="dataLoaded">
      <div class="group">
        <div class="header">
          <div class="title">组织机构</div>
          <div class="handler">
            <div class="showCode">
              <el-switch v-model="showCode" style="--el-switch-on-color: #54bcbd" /><span class="showCodeLabel">显示编码</span>
            </div>
          </div>
        </div>
        <div class="tree" v-loading="loading1">
          <ZTree :id="treeId" :zNodes="zNodes" :show-code="showCode" @click-dom="zTreeOnClick" />
        </div>
      </div>
      <div class="main">
        <div class="header">
          <div class="title">{{ dptName }}</div>
        </div>
        <div class="table-box" v-loading="loading">
          <ProTable
            ref="proTable"
            title="人员列表"
            rowKey="empid"
            :columns="columns"
            :request-api="getTableList"
            :data-callback="dataCallback"
            :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
            :small="true"
          >
            <!-- 表格 header 按钮 -->
            <template #tableHeader="scope">
              <el-button-group>
                <el-button type="primary" text :icon="CirclePlus" @click="openDrawer('新增')">新增</el-button>
                <el-button type="primary" text :icon="UploadFilled" @click="dialogVisible = true">导入</el-button>
                <el-button type="danger" text :icon="Delete" @click="_batchDel(scope.selectedListIds)">删除</el-button>
              </el-button-group>
              <el-button-group>
                <el-button type="primary" text :icon="Clock" @click="dialogVisible2 = true">改卡有效期</el-button>
                <el-button type="primary" text :icon="CreditCard" @click="dialogVisible1 = true">读卡查询</el-button>
              </el-button-group>
              <el-button-group>
                <el-button type="warning" text :icon="Lock" @click="_batchLock(scope.selectedListIds)">挂失</el-button>
                <el-button type="warning" text :icon="Unlock" @click="_batchUnLock(scope.selectedListIds)">解挂</el-button>
                <el-button type="danger" text :icon="Edit" @click="_batchResetPsd(scope.selectedListIds)">重置密码</el-button>
              </el-button-group>
            </template>
            <!-- Expand -->
            <template #expand="scope">
              {{ scope.row }}
            </template>
            <!-- 表格操作 -->
            <template #operation="scope">
              <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
              <el-button type="primary" link :icon="Key" @click="openDialog(scope.row)">修改密码</el-button>
            </template>
          </ProTable>
        </div>
      </div>
      <UploadDialog :dialog-visible="dialogVisible" :handle-close="handleClose" />
      <CardReadingDilalog :dialog-visible="dialogVisible1" :handle-close="handleClose" @read-card-cb="readCardCb" />
      <CardValidityDialog :orgUnitIDs="orgUnitIDs" :dialog-visible="dialogVisible2" :handle-close="handleClose" />
      <PasswordDialog ref="passwordRef" />
      <EmployeeDrawer ref="drawerRef" v-if="zNodes.length" />
    </div>
  </div>
</template>

<script setup lang="tsx" name="employeeManage">
/* eslint-disable */
// @ts-nocheck
import { onMounted, ref } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import ZTree from "@/components/ZTree/index.vue";
import CardReadingDilalog from "./components/CardReadingDilalog.vue";
import CardValidityDialog from "./components/CardValidityDialog.vue";
import UploadDialog from "./components/UploadDialog.vue";
import EmployeeDrawer from "./components/EmployeeDrawer.vue";
import PasswordDialog from "./components/PasswordDialog.vue";
import { ElMessage, ElMessageBox, ElUpload, UploadRequestOptions } from "element-plus";
import { downloadEvt, getAssetsFile } from "@/utils";
import { getOrgTree, getEcardTypes } from "@/api/modules/common";
import {
  CirclePlus,
  UploadFilled,
  Edit,
  EditPen,
  Delete,
  Clock,
  CreditCard,
  Lock,
  Unlock,
  Download,
  Key
} from "@element-plus/icons-vue";
import {
  getEmployeeList,
  addEmployee,
  editEmployee,
  delEmployee,
  lockCard,
  unlockCard,
  resetPsd,
  updatePsd,
  uploadExcle
} from "@/api/modules/cardIssuingCenter/employeeManage";
import JSEncrypt from "jsencrypt";

onMounted(() => {
  getEcardTypesFunc();
  getOrgTreeData();
});

const treeId = ref("tree");
const showCode = ref(false);
const dataLoaded = ref(false);
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const dialogVisible2 = ref(false);
const dialogVisible3 = ref(false);
const loading = ref(false);
const loading1 = ref(false);
const dptId = ref("");
const dptName = ref("");
const orgUnitIDs = ref([]);
const ecardTypes = ref([]);
const zNodes = ref([]);
const list = ref([]);
const proTable = ref();

const dataCallback = (data: any) => {
  const { records, page } = data;
  loading.value = false;
  list.value = records;
  return {
    list: records || [],
    total: page.total
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading.value = true;
  list.value = [];
  return getEmployeeList({ ...newParams, orgUnitIDs: orgUnitIDs.value });
};

const columns = [
  { type: "selection", fixed: "left", width: 60 },
  {
    prop: "clause",
    label: "",
    isShow: false,
    search: { el: "input" },
    minWidth: 120
  },
  {
    prop: "empcode",
    label: "编号",
    minWidth: 200
  },
  {
    prop: "empname",
    label: "姓名",
    minWidth: 120,
    render: scope => {
      return (
        <el-button type="primary" link>
          {scope.row.empname}
        </el-button>
      );
    }
  },
  {
    prop: "cardType",
    label: "部门",
    minWidth: 200
  },
  {
    prop: "cardvalid",
    label: "卡有效期",
    minWidth: 200
  },
  {
    prop: "rulevalid",
    label: "门禁有效期",
    minWidth: 200
  },

  {
    prop: "bcard",
    label: "发卡",
    minWidth: 120,
    render: scope => {
      return (
        <>
          <el-checkbox disabled v-model={scope.row.bcard}></el-checkbox>
        </>
      );
    }
  },
  {
    prop: "bfinger",
    label: "指纹",
    minWidth: 120,
    render: scope => {
      return (
        <>
          <el-checkbox disabled v-model={scope.row.bfinger}></el-checkbox>
        </>
      );
    }
  },
  {
    prop: "block",
    label: "挂失",
    minWidth: 120,
    render: scope => {
      return (
        <>
          <el-checkbox disabled v-model={scope.row.block}></el-checkbox>
        </>
      );
    }
  },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 180 }
];

/**
 * 修改密码
 */
const _editPsd = async row => {
  ElMessageBox.prompt("请输入新密码", "修改密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern:
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()\-_=+{};:,<.>])[a-zA-Z][a-zA-Z0-9!@#$%^&*()\-_=+{};:,<.>]{5,17}$/,
    inputErrorMessage: "密码6-18位(以字母开头，同时包含大写字母、小写字母、数字以及?=.*[!@#$%^&*()\-_=+{};:,<.>]特殊字符)",
    draggable: true,
    beforeClose: (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        const encryptor = new JSEncrypt();
        encryptor.setPublicKey(import.meta.env.VITE_PUBLIC_kEY);
        const stringParam1 = encryptor.encrypt(instance.inputValue) as string;
        try {
          await updatePsd({ id: row.empid, stringParam1 });
          ElMessage.success("密码修改成功");
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
};

// 批量删除人员信息
const _batchDel = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择要删除的人员");
    return false;
  }
  const tip = "删除所选人员信息";
  let count = 0;
  let isFail = false;

  ElMessageBox.confirm(`是否${tip}?`, "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
    beforeClose: (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        try {
          const res = await delEmployee({ list: selectedListIds });
          const { v1, v2 } = res.data;
          ElMessage.success(`删除成功：${v1},失败：${v2}`);
          proTable.value.clearSelection();
          proTable.value.getTableList();
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
};

// 批量挂失
const _batchLock = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择要挂失的卡片人员");
    return false;
  }

  const tip = "挂失所选人员卡片";
  let count = 0;
  let isFail = false;

  ElMessageBox.confirm(`是否${tip}?`, "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
    beforeClose: (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        selectedListIds = list.value.filter(item => item.bcard).filter(item => selectedListIds.includes(item.empid));
        if (!selectedListIds.length) {
          ElMessage.error("所选人员未发卡");
          instance.confirmButtonLoading = false;
          return false;
        }
        try {
          const res = await lockCard({ list: selectedListIds.map(item => item.empid) });
          const { v1, v2 } = res.data;
          ElMessage.success(`挂失成功：${v1},失败：${v2}`);
          proTable.value.clearSelection();
          proTable.value.getTableList();
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
};

// 批量解锁
const _batchUnLock = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择要解锁卡片的人员");
    return false;
  }
  const tip = "解锁所选人员卡片";
  let count = 0;
  let isFail = false;

  ElMessageBox.confirm(`是否${tip}?`, "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    beforeClose: (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        selectedListIds = list.value.filter(item => item.bcard).filter(item => selectedListIds.includes(item.empid));
        if (!selectedListIds.length) {
          ElMessage.error("所选人员未发卡");
          instance.confirmButtonLoading = false;
          return false;
        }
        try {
          const res = await unlockCard({ list: selectedListIds.map(item => item.empid) });
          const { v1, v2 } = res.data;
          ElMessage.success(`解锁成功：${v1},失败：${v2}`);
          proTable.value.clearSelection();
          proTable.value.getTableList();
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
};

// 重置密码
const _batchResetPsd = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择要重置密码的人员");
    return false;
  }
  const tip = "重置所选人员密码";
  let count = 0;
  let isFail = false;

  ElMessageBox.confirm(`是否${tip}?`, "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
    beforeClose: (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        selectedListIds = list.value.filter(item => item.bcard).filter(item => selectedListIds.includes(item.empid));
        if (!selectedListIds.length) {
          ElMessage.error("所选人员未发卡");
          instance.confirmButtonLoading = false;
          return false;
        }
        try {
          const res = await resetPsd({ list: selectedListIds.map(item => item.empid) });
          const { v1, v2 } = res.data;
          ElMessage.success(`重置密码成功：${v1},失败：${v2}`);
          proTable.value.clearSelection();
          proTable.value.getTableList();
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof EmployeeDrawer> | null>(null);
const openDrawer = (title: string, row = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row, dptname: dptName.value, dptid: dptId.value },
    api: title === "新增" ? addEmployee : title === "编辑" ? editEmployee : undefined,
    getTableList: proTable.value.getTableList,
    resetTableList: proTable.value.reset,
    ecardTypes: ecardTypes.value,
    zNodes
  };

  drawerRef.value?.acceptParams(params);
};

const passwordRef = ref<InstanceType<typeof PasswordDialog> | null>(null);
const openDialog = row => {
  passwordRef.value?.openDialog(row);
};

/**
 * 批量操作回调
 */
const batchCallBack = (tip, count, isFail, selectedListIds) => {
  if (count === selectedListIds.length) {
    if (!isFail) {
      ElMessage({
        type: "success",
        message: `${tip}成功!`
      });
    }
    loading.value = true;
    proTable.value.clearSelection();
    proTable.value.reset();
  }
};

/**
 * 读卡查询回调
 */
const readCardCb = list => {
  proTable.value.tableData = list;
};

/**
 * 点击树节点
 */
const zTreeOnClick = ({ treeNode, ids }) => {
  dptId.value = treeNode.id;
  dptName.value = treeNode.name;
  orgUnitIDs.value = ids;
  loading.value = true;
  proTable.value.clearSelection();
  proTable.value.getTableList();
};

/**
 * 关闭提示框
 */
const handleClose = () => {
  dialogVisible.value = false;
  dialogVisible1.value = false;
  dialogVisible2.value = false;
  dialogVisible3.value = false;
};

/**
 * 消息框关闭
 */
const beforeCloseFunc = async (action, instance, done, cb) => {
  if (action === "confirm") {
    instance.confirmButtonLoading = true;
    cb && cb();
  } else {
    done();
  }
};

/**
 * 获取组织树结构
 */
const getOrgTreeData = async () => {
  loading1.value = true;
  try {
    const res = await getOrgTree();
    zNodes.value = res.data;
    loading1.value = false;
  } catch (error) {
    console.log(error);
  }
};

/**
 * 获取员工卡类型
 */
const getEcardTypesFunc = async () => {
  dataLoaded.value = false;
  try {
    const res = await getEcardTypes();
    ecardTypes.value = res.data ?? [];
    dataLoaded.value = true;
  } catch (error) {
    dataLoaded.value = true;
    console.log(error);
  }
};
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
